﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class BaoZhangZhuangBeiTypeController : BaseController
    {
        private readonly ILogger<BaoZhangZhuangBeiTypeController> _logger;
        public BaoZhangZhuangBeiTypeController(ILogger<BaoZhangZhuangBeiTypeController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            List<BaoZhangZhuangBeiType> baozhangzhuangbeitypes = await _fsql.Select<BaoZhangZhuangBeiType>().Count(out var total).ToListAsync();
            _logger.LogInformation(_fsql.Select<BaoZhangZhuangBeiType>().ToSql());
            JObject data = new JObject();
            data.Add("total", total);
            data.Add("list", JArray.FromObject(baozhangzhuangbeitypes));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] BaoZhangZhuangBeiType baozhangzhuangbeitype)
        {
            long id = await _fsql.Insert(baozhangzhuangbeitype).ExecuteIdentityAsync();
            baozhangzhuangbeitype.Id = id;

            return RenderJson(data: baozhangzhuangbeitype);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = await _fsql.Delete<BaoZhangZhuangBeiType>().Where(bzzbt => bzzbt.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] BaoZhangZhuangBeiType baozhangzhuangbeitype) {
            _logger.LogInformation("保障装备更新信息：" + baozhangzhuangbeitype.ToString());
            int affrows = await _fsql.Update<BaoZhangZhuangBeiType>().SetSourceIgnore(baozhangzhuangbeitype, colval => colval == null).ExecuteAffrowsAsync();
            BaoZhangZhuangBeiType data = await _fsql.Select<BaoZhangZhuangBeiType>().Where(bzzbt => bzzbt.Id == baozhangzhuangbeitype.Id).ToOneAsync();
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            BaoZhangZhuangBeiType baozhangzhuangbeitype = await _fsql.Select<BaoZhangZhuangBeiType>().Where(bzzbt => bzzbt.Id == id).ToOneAsync();
            //JObject data = JObject.FromObject(baozhangzhuangbeitype);
            //data.Add("gzfieldinfo_json", JObject.Parse(baozhangzhuangbeitype.Gzfieldinfo));
            return RenderJson(data: baozhangzhuangbeitype);
        }
    }
}
